package zt.song.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import zt.song.domain.Perm;
import zt.song.domain.User;
import zt.song.mapper.PermMapper;
import zt.song.service.UserService;
import zt.song.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 宋伟宁
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2023-11-18 09:38:23
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;


    @Resource
    private PermMapper permMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账号查询是否存在用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        //var是jdk11后推出的一个新特性：隐藏数据类型
        var user = this.userMapper.selectOne(userQueryWrapper);
        // 判断是否存在
        if(null  == user){
            throw  new UsernameNotFoundException("对不起，账号不存在！");
        }
        // 获取用户的角色或权限（ ROLE_***:角色 ****:权限）
        QueryWrapper<Perm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        List<Perm> perms = this.permMapper.selectList(queryWrapper);
        //转换未权限或角色的Stirng
        List<String> auths= perms.stream().map(Perm::getTag).collect(Collectors.toList());
        user.setAuthorities(AuthorityUtils.createAuthorityList(auths));
        return user;
    }
}




